#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <atomic>
#include <thread>

class Demo {
public:
    Demo() {
        printf("init Demo.\n");
        m_loop_run = true;
        m_th1 = std::thread([](std::atomic_bool* loop_run){
            printf("th1 enter.\n");
            while (*loop_run) {
                printf("> th1.\n");
                sleep(2);
            }
            printf("th1 exit.\n");
        }, &m_loop_run);
        m_th2 = std::thread([](std::atomic_bool* loop_run){
            printf("th2 enter.\n");
            while (*loop_run) {
                printf("> th2.\n");
                sleep(2);
            }
            printf("th2 exit.\n");
        }, &m_loop_run);
        m_th3 = std::thread([](std::atomic_bool* loop_run){
            printf("th3 enter.\n");
            while (*loop_run) {
                printf("> th3.\n");
                sleep(2);
            }
            printf("th3 exit.\n");
        }, &m_loop_run);
        m_th4 = std::thread([](std::atomic_bool* loop_run){
            printf("th4 enter.\n");
            while (*loop_run) {
                printf("> th4.\n");
                sleep(2);
            }
            printf("th4 exit.\n");
        }, &m_loop_run);

        printf("init Demo seccess.\n");
    };

    ~Demo() {
        printf("deinit Demo.\n");
        m_loop_run = false;
        if (m_th1.joinable()) {
            m_th1.join();
        }
        if (m_th2.joinable()) {
            m_th2.join();
        }
        if (m_th3.joinable()) {
            m_th3.join();
        }
        if (m_th4.joinable()) {
            m_th4.join();
        }
        printf("deinit Demo seccess.\n");
    }
private:
    std::atomic_bool m_loop_run;
    std::thread m_th1;
    std::thread m_th2;
    std::thread m_th3;
    std::thread m_th4;
};

static std::atomic_bool proc_loop_run;
static void signal_handler(int signal)
{
    proc_loop_run = false;
}

int main(int argc, char* argv[])
{
    proc_loop_run = true;
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);

    Demo d;

    while (proc_loop_run) { sleep(1); }
    return 0;
}